/**
 * Malsha Sewwandi 2014-06-27
 */

JournalEntry = new Object();

var journal_entry_store = Ext.create('Ext.data.Store', {
	fields : [ 'id', 'accountNo1', 'accountNo2', 'accountNo3', 'amount', 'amount1', 'amount2', 'amount3', 'confirmedUser', 'creditDebit', 'custoemrName', 'customerId',
			'customerType', 'description1', 'description2', 'description3', 'enteredUser', 'fundId', 'journalDate', 'status', 'customer' ]
});

var accounting_store = Ext.create('Ext.data.Store', {
	fields : [ 'id', 'accountNo', 'description' ]
});

var fund_store = Ext.create('Ext.data.Store', {
	fields : [ 'id', 'name', 'code', 'unitValue' ]
});

var journalid = null;
var customerId = null;
var customerType = null;

JournalEntry.getBasicDetails = function() {
	return Ext.create('Ext.form.FieldSet', {

		defaults : {
			anchor : '100%'
		},
		items : [ {
			xtype : 'combo',
			fieldLabel : 'Fund<span style="color:red">*</span>',
			flex : 1,
			labelWidth : 85,
			anchor : '70%',
			id : 'fund',
			padding : '0 10 0 0',
			store : fund_store,
			valueField : 'id',
			displayField : 'code',
			emptyText : 'Select a Fund...',
			isLoaded : false,
			allowBlank : false,
			msgTarget : 'under',
			name : 'fundId',
			queryMode : 'local',
			tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - {name}</div>', '</tpl>'),
			displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {name}', '</tpl>'),
			listeners : {
				expand : function(combo, opt) {
					if (!combo.isLoaded) {
						Ext.Ajax.request({
							url : 'getFundVsUnitValue.action',
							success : function(response) {
								var obj = Ext.decode(response.responseText);
								combo.getStore().loadRawData(obj.fundDtos);
								combo.isLoaded = true;
							}
						});
					}
				}
			}
		}, {
			xtype : 'datefield',
			fieldLabel : 'Date',
			name : 'journalDate',
			labelWidth : 85,
			format : 'd/m/Y',
			anchor : '40%',
		}, {
			xtype : 'textfield',
			fieldLabel : 'Amount',
			labelWidth : 85,
			anchor : '60%',
			name : 'amount',
			fieldStyle : "text-align:right;",
			maskRe : /[\d\,.]/,
			listeners : {
				blur : function() {
					this.setRawValue(Ext.util.Format.number(this.value.replace(/,/g, ''), '0,000.0000'));
				},
				render : function(p) {
					this.setRawValue(Ext.util.Format.number(this.value, '0,000.0000'));
				}
			}
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'triggerfield',
				emptyText : 'Search Customer',
				triggerCls : 'x-form-search-trigger',
				fieldLabel : 'Customer',
				id : 'customer',
				name : 'customer',
				padding : '0 15 0 0',
				labelWidth : 85,
				onTriggerClick : function() {
					var window = null;
					if (!window) {
						window = Ext.create('Ext.window.Window', {
							title : 'Customer',
							height : 330,
							frame : true,
							width : 500,
							constrain : true,
							resizable : false,
							modal : true,
							layout : {
								type : 'accordion',
								animate : true,
								hideCollapseTool : true,
							},
							items : [ {
								xtype : 'form',
								title : 'Search Criteria',
								bodyPadding : 20,
								autoScroll : true,
								frame : true,
								items : [ {
									xtype : 'fieldcontainer',
									fieldLabel : 'Customer Type',
									defaultType : 'radiofield',
									layout : 'hbox',
									items : [ {
										boxLabel : 'Customer',
										name : 'customerType',
										padding : '0 5 0 0',
										checked : true,
										inputValue : 'CUS',
									}, {
										boxLabel : 'Issuer',
										name : 'customerType',
										padding : '0 5 0 0',
										inputValue : 'ISU',
									}, {
										boxLabel : 'Other',
										name : 'customerType',
										inputValue : 'O',
									} ]
								}, {
									xtype : 'textfield',
									fieldLabel : 'Code',
									name : 'customerCode',
								}, {
									xtype : 'textfield',
									fieldLabel : 'Name',
									name : 'customerName',
								} ],
								buttonAlign : 'center',
								buttons : [ {
									text : 'Reset',
									handler : function() {
										this.up('form').getForm().reset();
									}
								}, {
									text : 'Search',
									handler : function() {
										var form = this.up('form').getForm();
										if (form.isValid()) {
											form.url = 'getCustomerByType.action';
											form.submit({
												success : function(form, action, response) {
													gidplen = Ext.getCmp('search_result');
													var obj = Ext.decode(action.response.responseText);
													gidplen.getStore().removeAll();
													gidplen.getStore().loadRawData(obj.allCustomers);
													gidplen.expand();
												},
												failure : function(form, action) {
													Ext.Msg.alert('Failed', action.result.resulteMsg);
												}
											});
										}
									}
								} ]
							}, new Ext.grid.Panel({
								title : 'Search Result',
								id : 'search_result',
								store : Ext.create('Ext.data.Store', {
									fields : [ 'customerId', 'customerType', 'customerCode', 'customerName' ]
								}),
								columns : [ {
									text : 'Customer Code',
									dataIndex : 'customerCode',
									flex : 1
								}, {
									text : 'Name',
									dataIndex : 'customerName',
									flex : 1.4
								} ],
								listeners : {
									itemdblclick : function(dv, record, item, index, e) {
										var data = record.data;
										Ext.getCmp('customer').setValue(data.customerCode);
										Ext.getCmp('customerName').setValue(data.customerName);
										Ext.getCmp('customerId').setValue(data.customerId);
										Ext.getCmp('customerType').setValue(data.customerType);
										window.close();
									}
								}
							}) ]
						});
					}
					if (window.isVisible()) {
						window.hide();
					} else {
						window.show();
					}
				}
			}, {
				xtype : 'textfield',
				fieldLabel : 'Customer Name',
				id : 'customerName',
				name : 'custoemrName',
				flex : 1.5
			}, {
				xtype : 'hiddenfield',
				name : 'customerId',
				id : 'customerId'
			}, {
				xtype : 'hiddenfield',
				name : 'customerType',
				id : 'customerType'
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			fieldLabel : 'Credit/ Debit',
			defaultType : 'radiofield',
			items : [ {
				boxLabel : 'Credit',
				name : 'creditDebit',
				id : 'redio_credit',
				inputValue : 'C',
				checked : true,
				padding : '0 20 0 0'
			}, {
				boxLabel : 'Debit',
				name : 'creditDebit',
				id : 'redio_debit',
				inputValue : 'D'
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'combo',
				fieldLabel : '1.Account No.',
				padding : '20 5 0 0',
				labelWidth : 85,
				flex : 1,
				name : 'accountNo1',
				store : accounting_store,
				valueField : 'accountNo',
				displayField : 'accountNo',
				isLoaded : false,
				editable : false,
				listeners : {
					expand : function(combo, opt) {
						if (!combo.isLoaded) {
							Ext.Ajax.request({
								url : 'getAccounting.action',
								success : function(response) {
									var obj = Ext.decode(response.responseText);
									combo.getStore().loadRawData(obj.accountDtos);
									combo.isLoaded = true;
								}
							});
						}
					},
				},
				listConfig : {
					listeners : {
						itemclick : function(list, record) {
							if (record.get('accountNo') != null && record.get('description') != null) {
								Ext.getCmp('description1').setValue(record.get('description'));
							}
						}
					}
				}
			}, {
				xtype : 'textfield',
				fieldLabel : 'Description',
				name : 'description1',
				id : 'description1',
				labelWidth : 70,
				padding : '20 5 0 0',
				flex : 1
			}, {
				xtype : 'textfield',
				fieldLabel : 'Amount',
				labelWidth : 50,
				padding : '20 0 0 0',
				flex : 1,
				name : 'amount1',
				fieldStyle : "text-align:right;",
				maskRe : /[\d\,.]/,
				listeners : {
					blur : function() {
						var val = this.value.replace(/,/g, '');
						this.setRawValue(Ext.util.Format.number(val, '0,000.0000'));
					},
					render : function() {
						this.setRawValue(Ext.util.Format.number(this.value, '0,000.0000'));
					}
				}
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'combo',
				fieldLabel : '2.Account No.',
				flex : 1,
				labelWidth : 85,
				name : 'accountNo2',
				padding : '0 5 0 0',
				store : accounting_store,
				valueField : 'accountNo',
				displayField : 'accountNo',
				isLoaded : false,
				editable : false,
				listeners : {
					expand : function(combo, opt) {
						if (!combo.isLoaded) {
							Ext.Ajax.request({
								url : 'getAccounting.action',
								success : function(response) {
									var obj = Ext.decode(response.responseText);
									combo.getStore().loadRawData(obj.accountDtos);
									combo.isLoaded = true;
								}
							});
						}
					},
				},
				listConfig : {
					listeners : {
						itemclick : function(list, record) {
							if (record.get('accountNo') != null && record.get('description') != null) {
								Ext.getCmp('description2').setValue(record.get('description'));
							}
						}
					}
				}
			}, {
				xtype : 'textfield',
				fieldLabel : 'Description',
				name : 'description2',
				id : 'description2',
				labelWidth : 70,
				flex : 1,
				padding : '0 5 0 0'
			}, {
				xtype : 'textfield',
				fieldLabel : 'Amount',
				labelWidth : 50,
				flex : 1,
				name : 'amount2',
				fieldStyle : "text-align:right;",
				maskRe : /[\d\,.]/,
				listeners : {
					blur : function() {
						var val = this.value.replace(/,/g, '');
						this.setRawValue(Ext.util.Format.number(val, '0,000.0000'));
					},
					render : function() {
						this.setRawValue(Ext.util.Format.number(this.value, '0,000.0000'));
					}
				}
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'combo',
				fieldLabel : '3.Account No.',
				flex : 1,
				labelWidth : 85,
				name : 'accountNo3',
				padding : '0 5 0 0',
				store : accounting_store,
				valueField : 'accountNo',
				displayField : 'accountNo',
				isLoaded : false,
				editable : false,
				listeners : {
					expand : function(combo, opt) {
						if (!combo.isLoaded) {
							Ext.Ajax.request({
								url : 'getAccounting.action',
								success : function(response) {
									var obj = Ext.decode(response.responseText);
									combo.getStore().loadRawData(obj.accountDtos);
									combo.isLoaded = true;
								}
							});
						}
					},
				},
				listConfig : {
					listeners : {
						itemclick : function(list, record) {
							if (record.get('accountNo') != null && record.get('description') != null) {
								Ext.getCmp('description3').setValue(record.get('description'));
							}
						}
					}
				}
			}, {
				xtype : 'textfield',
				fieldLabel : 'Description',
				labelWidth : 70,
				name : 'description3',
				id : 'description3',
				flex : 1,
				padding : '0 5 0 0'
			}, {
				xtype : 'textfield',
				fieldLabel : 'Amount',
				labelWidth : 50,
				flex : 1,
				name : 'amount3',
				fieldStyle : "text-align:right;",
				maskRe : /[\d\,.]/,
				listeners : {
					blur : function() {
						var val = this.value.replace(/,/g, '');
						this.setRawValue(Ext.util.Format.number(val, '0,000.0000'));
					},
					render : function() {
						this.setRawValue(Ext.util.Format.number(this.value, '0,000.0000'));
					}
				}
			} ]
		} ]
	});
};

JournalEntry.getCeneterPanel = function() {

	return formPanel = Ext.create('Ext.form.Panel', {
		title : 'Journal Entry',
		titleAlign : 'left',
		id : 'journalEntryForm',
		bodyPadding : '20',
		autoScroll : true,
		defaults : {
			anchor : '65%'
		},
		frame : true,
		items : [ {
			xtype : 'fieldcontainer',
			items : [ {
				xtype : 'triggerfield',
				emptyText : 'Search Journal Entry',
				triggerCls : 'x-form-search-trigger',
				width : 300,
				style : 'float:right;',
				onTriggerClick : function() {
					var window = null;
					Ext.Ajax.request({
						url : 'getJournalEntry.action',
						success : function(response) {
							var obj = Ext.decode(response.responseText);
							journal_entry_store.removeAll();
							journal_entry_store.loadRawData(obj.entryDtos);
						}
					});
					if (!window) {
						window = Ext.create('Ext.window.Window', {
							title : 'Journal Entry',
							height : 330,
							frame : true,
							width : 500,
							constrain : true,
							resizable : false,
							modal : true,
							layout : {
								type : 'fit'
							},
							items : [ {
								xtype : 'gridpanel',
								defaults : {
									anchor : '100%'
								},
								store : journal_entry_store,
								columns : [ {
									text : 'Id',
									dataIndex : 'id',
									flex : 1
								}, {
									text : 'Name',
									dataIndex : 'custoemrName',
									flex : 1.4
								}, {
									text : 'Amount',
									dataIndex : 'amount',
									flex : 1,
									align : 'right'
								} ],
								listeners : {
									itemdblclick : function(dv, record, item, index, e) {
										var data = record.data;
										JournalEntry.setFormFields(data, record);
										window.hide();
									}
								}
							} ]
						});
					}
					;
					if (window.isVisible()) {
						window.hide();
					} else {
						window.show();
					}

				}
			} ]
		}, JournalEntry.getBasicDetails() ],
		buttonAlign : 'center',
		buttons : [ {
			text : 'Cancel',
			handler : function() {
				App.Core.removeScreen();
			}
		}, {
			text : 'Reset',
			handler : function() {
				this.up('form').getForm().reset();
				journalid = null;
			}
		}, {
			text : 'Save',
			id : 'save',
			handler : function() {
				var form = this.up('form').getForm();
				if (form.isValid()) {
					formPanel.setLoading('Saving...');
					if (journalid == null) {
						form.url = 'addJournalEntry.action';
						form.submit({
							success : function(form, action) {
								form.reset();
								Ext.Msg.alert('Success', 'Saved Successfully');
								formPanel.setLoading(false);
								journalid = null;
								Ext.getCmp('save').setText('Save');
							},
							failure : function(form, action) {
								Ext.Msg.alert('Failed', action.result.resultMsg);
								formPanel.setLoading(false);
							}
						});
					} else {
						form.url = 'UpdateJournalEntry.action';
						form.submit({
							params : {
								"journalid" : journalid
							},
							success : function(form, action) {
								form.reset();
								Ext.Msg.alert('Success', 'Saved Successfully');
								formPanel.setLoading(false);
								journalid = null;
								Ext.getCmp('save').setText('Save');
							},
							failure : function(form, action) {
								Ext.Msg.alert('Failed', action.result.resultMsg);
								formPanel.setLoading(false);
							}
						});
					}
				}
			}
		}, {
			text : 'Confirm',
			id : 'confirm',
			disabled : true,
			handler : function() {
				var form = this.up('form').getForm();
				if (journalid != null) {
					if (form.isValid()) {
						console.log(journalid);
						form.url = 'confirmJournal.action';
						form.submit({
							params : {
								"journalid" : journalid
							},
							success : function(form, action) {
								form.reset();
								journalid = null;
								Ext.getCmp('save').setText('Save');
								Ext.Msg.alert('Success', 'Confirmed Successfully');
							},
							failure : function(form, action) {
								Ext.Msg.alert('Failed', action.result.resulteMsg);
							}
						});
					}
				} else {
					Ext.Msg.alert('Info', 'Select the Journal Entry');
				}
			}
		}, {
			text : 'Reject',
			id : 'reject',
			disabled : true,
			handler : function() {
				var form = this.up('form').getForm();
				if (journalid != null) {
					if (form.isValid()) {
						form.submit({
							url : 'rejectJournal.action',
							method : 'GET',
							params : {
								"journalid" : journalid
							},
							success : function(form, action) {
								form.reset();
								journalid = null;
								Ext.getCmp('save').setText('Save');
								Ext.Msg.alert('Success', 'Journal Entry Reject');
							},
							failure : function(form, action) {
								Ext.Msg.alert('Failed', action.result.resulteMsg);
							}
						});
					}
				} else {
					Ext.Msg.alert('Info', 'Select the Journal Entry');
				}
			}
		} ]
	});
};

JournalEntry.setFormFields = function(data, record) {
	var formPanl = Ext.getCmp('journalEntryForm');
	journalid = data.id;
	Ext.getCmp('save').setText('Update');

	Ext.Ajax.request({
		url : 'getFundVsUnitValue.action',
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			fund_store.loadRawData(obj.fundDtos);
		}
	});

	Ext.Ajax.request({
		url : 'getAccounting.action',
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			accounting_store.loadRawData(obj.accountDtos);
		}
	});

	formPanl.getForm().loadRecord(record);

	if (data.status == "INITIAL") {
		if (App.screenPermiton.getAt(0).data.create == 0)
			Ext.getCmp('save').disable();
		else
			Ext.getCmp('save').enable();

		if (App.screenPermiton.getAt(0).data.confirm == 0)
			Ext.getCmp('confirm').disable();
		else
			Ext.getCmp('confirm').enable();

		if (App.screenPermiton.getAt(0).data.reject == 0)
			Ext.getCmp('reject').disable();
		else
			Ext.getCmp('reject').enable();
		Ext.getCmp('save').setText('Update');
		formPanl.getForm().loadRecord(record);
	} else if (data.status == "CONFIRM") {
		Ext.getCmp('save').disable();
		Ext.getCmp('confirm').disable();
		Ext.getCmp('reject').disable();
		formPanl.getForm().loadRecord(record);
	} else {
		Ext.getCmp('save').disable();
		Ext.getCmp('reject').disable();
		Ext.getCmp('confirm').disable();
		formPanl.getForm().loadRecord(record);
	}
};